<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="消息标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入消息标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消息类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择消息类型" clearable>
          <el-option
            v-for="dict in typeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="阅读状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择阅读状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['message:sysMessage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['message:sysMessage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['message:sysMessage:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="消息ID" align="center" prop="messageId" width="80" />
      <el-table-column label="消息标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="消息类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag :type="typeTagType(scope.row.type)">{{ typeFormat(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="阅读状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 ? 'danger' : 'success'">
            {{ scope.row.status === 0 ? '未读' : '已读' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="相关订单" align="center" prop="orderNumber" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['message:sysMessage:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['message:sysMessage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['message:sysMessage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择消息类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入消息内容" :rows="5" />
        </el-form-item>
        <el-form-item label="相关订单" prop="orderNumber" v-if="form.type === 1">
          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="服务项目" prop="serviceItem" v-if="form.type === 1">
          <el-input v-model="form.serviceItem" placeholder="请输入服务项目" />
        </el-form-item>
        <el-form-item label="上门时间" prop="visitTime" v-if="form.type === 1">
          <el-date-picker
            v-model="form.visitTime"
            type="datetime"
            placeholder="选择上门时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone" v-if="form.type === 1">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看消息对话框 -->
    <el-dialog title="消息详情" :visible.sync="viewDialogVisible" width="600px" append-to-body>
      <el-descriptions class="message-detail" :column="1" border>
        <el-descriptions-item label="消息ID">{{ viewForm.messageId }}</el-descriptions-item>
        <el-descriptions-item label="消息标题">{{ viewForm.title }}</el-descriptions-item>
        <el-descriptions-item label="消息类型">
          <el-tag :type="typeTagType(viewForm.type)">{{ typeFormat(viewForm.type) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="消息内容">
          <div class="message-content">{{ viewForm.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="相关订单" v-if="viewForm.orderNumber">
          {{ viewForm.orderNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="服务项目" v-if="viewForm.serviceItem">
          {{ viewForm.serviceItem }}
        </el-descriptions-item>
        <el-descriptions-item label="上门时间" v-if="viewForm.visitTime">
          {{ viewForm.visitTime }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话" v-if="viewForm.contactPhone">
          {{ viewForm.contactPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="阅读状态">
          <el-tag :type="viewForm.status === 0 ? 'danger' : 'success'">
            {{ viewForm.status === 0 ? '未读' : '已读' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="markAsRead(viewForm.messageId)" v-if="viewForm.status === 0">标记为已读</el-button>
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMessage, getMessage, delMessage, addMessage, updateMessage, readMessage } from "@/api/company/message";

export default {
  name: "SysMessage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息表格数据
      messageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewDialogVisible: false,
      // 日期范围
      dateRange: [],
      // 消息类型选项
      typeOptions: [
        { value: 1, label: "订单通知" },
        { value: 2, label: "系统消息" },
        { value: 3, label: "客服消息" },
        { value: 4, label: "社区互动" }
      ],
      // 阅读状态选项
      statusOptions: [
        { value: 0, label: "未读" },
        { value: 1, label: "已读" }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        type: null,
        status: null
      },
      // 表单参数
      form: {},
      // 查看表单
      viewForm: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "消息标题不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "消息类型不能为空", trigger: "change" }
        ],
        content: [
          { required: true, message: "消息内容不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询消息列表 */
    getList() {
      this.loading = true;
      listMessage(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.messageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        messageId: null,
        title: null,
        content: null,
        type: 2,
        status: 0,
        orderNumber: null,
        serviceItem: null,
        visitTime: null,
        contactPhone: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    // 消息类型字典翻译
    typeFormat(type) {
      const typeMap = {
        1: '订单通知',
        2: '系统消息',
        3: '客服消息',
        4: '社区互动'
      };
      return typeMap[type] || '';
    },
    // 消息类型标签类型
    typeTagType(type) {
      const typeMap = {
        1: 'primary',
        2: 'info',
        3: 'success',
        4: 'warning'
      };
      return typeMap[type] || '';
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.messageId);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加消息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const messageId = row.messageId || this.ids[0];
      getMessage(messageId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改消息";
      });
    },
    /** 查看详情操作 */
    handleView(row) {
      getMessage(row.messageId).then(response => {
        this.viewForm = response.data;
        this.viewDialogVisible = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.messageId != null) {
            // 设置更新者和更新时间
            this.form.updateBy = this.$store.getters.name;
            // 使用parseTime格式化日期为后端期望的格式
            this.form.updateTime = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
            
            updateMessage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 设置默认值
            if (this.form.status === undefined) {
              this.form.status = 0;
            }
            
            // 设置创建者和创建时间
            this.form.createBy = this.$store.getters.name;
            // 使用parseTime格式化日期为后端期望的格式
            this.form.createTime = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
            
            addMessage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const messageIds = row.messageId || this.ids;
      this.$modal.confirm('是否确认删除消息编号为"' + messageIds + '"的数据项？').then(function() {
        return delMessage(messageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 标记为已读 */
    markAsRead(messageId) {
      readMessage(messageId).then(response => {
        this.viewForm.status = 1;
        this.$modal.msgSuccess("已标记为已读");
        this.getList();
      });
    }
  }
};
</script>

<style scoped>
.message-content {
  white-space: pre-wrap;
  word-break: break-all;
  min-height: 80px;
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}
</style> 